import GUI from "lil-gui";
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import Stats from "three/examples/jsm/libs/stats.module";

class Gui {
  lightY: number; //灯光y轴的位置
  cubeY: number; //球的z轴的位置
  cubeX: number; //立方体的x轴位置
  cubeZ: number; //立方体的z轴的位置
  // 构造函数
  constructor(lightY = 30, cubeX = 25, cubeY = 10, cubeZ = -5) {
    this.lightY = lightY;
    this.cubeX = cubeX;
    this.cubeY = cubeY;
    this.cubeZ = cubeZ;
  }
}

export default class ThreeJs {
  gui: Gui | null = null;
  stats: Stats | null = null;
  scene: THREE.Scene | null = null;
  camera: THREE.PerspectiveCamera | null = null;
  light: THREE.PointLight | null = null;
  renderer: THREE.WebGLRenderer | null = null;
  ambientLight: THREE.AmbientLight | null = null;
  cube: THREE.Mesh | null = null;
  controls: OrbitControls | null = null;

  constructor() {
    this.init();
  }

  init(): void {
    this.initGui();
    this.initRender();
    this.initScene();
    this.initCamera();
    this.initLight();
    this.initModel();
    this.initControls();
    this.initStats();
    this.animate();
    this.onWindowResize();
  }

  onWindowResize(): void {
    window.addEventListener("resize", () => {
      if (this.camera && this.renderer) {
        this.camera.aspect = window.innerWidth / window.innerHeight;
        this.camera.updateProjectionMatrix();
        this.render();
        this.renderer.setSize(window.innerWidth, window.innerHeight);
      }
    });
  }

  initGui(): void {
    //声明一个保存需求修改的相关数据的对象
    this.gui = new Gui();
    const datGui = new GUI();
    //将设置属性添加到gui当中，gui.add(对象，属性，最小值，最大值）
    datGui.add(this.gui, "lightY", 0, 100);
    datGui.add(this.gui, "cubeX", -30, 30);
    datGui.add(this.gui, "cubeY", -30, 30);
    datGui.add(this.gui, "cubeZ", -30, 30);
  }

  initScene(): void {
    this.scene = new THREE.Scene();
  }

  // 新建透视相机
  initCamera(): void {
    // 第二参数就是 长度和宽度比 默认采用浏览器  返回以像素为单位的窗口的内部宽度和高度
    this.camera = new THREE.PerspectiveCamera(
      45,
      window.innerWidth / window.innerHeight,
      0.1,
      1000
    );
    this.camera.position.set(0, 40, 100);
    this.camera.lookAt(new THREE.Vector3(0, 0, 0));
  }

  // 设置渲染器
  initRender(): void {
    this.renderer = new THREE.WebGLRenderer({ antialias: true });
    // 设置画布的大小
    this.renderer.setSize(window.innerWidth, window.innerHeight);
    //告诉渲染器需要阴影效果
    this.renderer.shadowMap.enabled = true;
    this.renderer.shadowMap.type = THREE.PCFSoftShadowMap; // 默认的是，没有设置的这个清晰 THREE.PCFShadowMap
    //这里 其实就是canvas 画布  renderer.domElement
    document.body.appendChild(this.renderer.domElement);
  }

  // 设置环境光
  initLight(): void {
    this.scene && this.scene.add(new THREE.AmbientLight(0x444444));
    this.light = new THREE.PointLight(0xffffff);
    this.light.position.set(15, 30, 10);
    //告诉平行光需要开启阴影投射
    this.light.castShadow = true;
    this.scene && this.scene.add(this.light);
  }

  // 创建网格模型
  initModel(): void {
    const boxMaterialShader = {
      vertexShader: `
      attribute vec3 aPosition;
      attribute vec4 aColor;
      varying vec4 vColor;
      void main(){
        vColor = aColor;
        gl_Position = projectionMatrix * modelViewMatrix * vec4(aPosition, 1.0);
      }
    `,
      fragmentShader: `
      varying vec4 vColor;
      void main(){
        gl_FragColor = vColor;
      }
    `,
    };

    if (this.scene) {
      //辅助工具
      const helper = new THREE.AxesHelper(10);
      this.scene.add(helper);

      // 创建一个立方体
      //    v6----- v5
      //   /|      /|
      //  v1------v0|
      //  | |     | |
      //  | |v7---|-|v4
      //  |/      |/
      //  v2------v3

      //立方体
      const cubeGeometry = new THREE.BufferGeometry();
      // 创建一个简单的矩形. 在这里我们左上和右下顶点被复制了两次。
      // 因为在两个三角面片里，这两个顶点都需要被用到。
      //创建立方体的顶点
      // const vertices = new Float32Array([
      //   // 三角形1 - 三个顶点
      //   -10, 10, 0, -10, -10, 0, 10, -10, 0,
      //   // 三角形2 - 三个顶点
      //   10, -10, 0, 10, 10, 0, -10, 10, 0,
      // ]);

      // 每六个坐标形成一个平面，6个平面合并成封闭的一个立方形
      const v0 = [10, 10, 10];
      const v1 = [-10, 10, 10];
      const v2 = [-10, -10, 10];
      const v3 = [10, -10, 10];
      const v4 = [10, -10, -10];
      const v5 = [10, 10, -10];
      const v6 = [-10, 10, -10];
      const v7 = [-10, -10, -10];
      // 第一个平面（左）
      const left = [...v1, ...v7, ...v2, ...v1, ...v6, ...v7];
      // 第二个平面（右）
      const right = [...v0, ...v3, ...v4, ...v0, ...v4, ...v5];
      // 第三个平面（上）
      const top = [...v0, ...v6, ...v1, ...v0, ...v5, ...v6];
      // 第四个平面（下）
      const bottom = [...v2, ...v4, ...v3, ...v7, ...v4, ...v2];
      // 第五个平面（前）
      const before = [...v2, ...v3, ...v1, ...v0, ...v1, ...v3];
      // 第六个平面（后）
      const after = [...v4, ...v6, ...v5, ...v4, ...v7, ...v6];
      const vertices = new Float32Array([
        ...left,
        ...right,
        ...top,
        ...bottom,
        ...before,
        ...after,
      ]);
      cubeGeometry.setAttribute(
        "position",
        new THREE.BufferAttribute(vertices, 3)
      );

      // const colors = new Float32Array([
      //   ...fontColor, // 前 index 0-3
      //   ...rightColor, // 右 index 4-7
      //   ...topColor, // 上 index 8-11
      //   ...leftColor, // 左 index 12-15
      //   ...downColor, // 下 index 16-19
      //   ...backColor, // 后 index 20-23
      // ]);

      // console.log(colors);
      // const colorAttribute = new THREE.BufferAttribute(colors, 4);
      // colorAttribute.normalized = true;
      // //设置颜色信息
      // cubeGeometry.setAttribute("color", colorAttribute);

      // 第一个平面（左）
      const leftIndex = [1, 7, 2, 1, 6, 7];
      // 第二个平面（右）
      const rightIndex = [0, 3, 4, 0, 4, 5];
      // 第三个平面（上）
      const topIndex = [0, 6, 1, 0, 5, 6];
      // 第四个平面（下）
      const bottomIndex = [2, 4, 3, 7, 4, 2];
      // 第五个平面（前）
      const beforeIndex = [2, 3, 1, 0, 1, 3];
      // 第六个平面（后）
      const afterIndex = [4, 6, 5, 4, 7, 6];
      const indexs = new Uint16Array([
        ...leftIndex,
        ...rightIndex,
        ...topIndex,
        ...bottomIndex,
        ...beforeIndex,
        ...afterIndex,
      ]);
      //设置画面的索引
      cubeGeometry.setAttribute("index", new THREE.BufferAttribute(indexs, 1));

      // 立方体;
      // const leftUv = [0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1]; //  图片的左下
      // const rightUv = [0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1]; // 图片右下
      // const beforUv = [0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1]; //图片中左
      // const afterUv = [0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1]; // 图片中右
      // const topUv = [0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1]; //图片左上
      // const bottomUv = [0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1]; // 图片右上
      // const uvs = new Float32Array([
      //   ...leftUv,
      //   ...rightUv,
      //   ...beforUv,
      //   ...afterUv,
      //   ...topUv,
      //   ...bottomUv,
      // ]);

      // //设置UV
      // cubeGeometry.setAttribute("uv", new THREE.BufferAttribute(uvs, 2));

      // 获取到纹理;
      // const cubeTexture = new THREE.TextureLoader().load(
      //   "/assets/imgs/dalishi.jpg"
      // );

      // const cubeMaterial = new THREE.MeshBasicMaterial({
      //   side: THREE.DoubleSide,
      //   map: cubeTexture,
      // });

      const cubeMaterial = new THREE.ShaderMaterial({
        side: THREE.DoubleSide,
        vertexShader: boxMaterialShader.vertexShader,
        fragmentShader: boxMaterialShader.fragmentShader,
      });

      cubeMaterial.needsUpdate = true;

      this.cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
      this.cube.position.x = 25;
      this.cube.position.y = 5;
      this.cube.position.z = -5;

      //告诉立方体需要投射阴影
      this.cube.castShadow = true;

      this.scene.add(this.cube);
      console.log(this.cube);
      //底部平面
      const planeGeometry = new THREE.PlaneGeometry(100, 100);
      const planeMaterial = new THREE.MeshLambertMaterial({ color: 0xaaaaaa });

      const plane = new THREE.Mesh(planeGeometry, planeMaterial);
      plane.rotation.x = -0.5 * Math.PI;
      plane.position.y = -0;

      //告诉底部平面需要接收阴影
      plane.receiveShadow = true;

      this.scene.add(plane);
    }
  }

  // 渲染
  render(): void {
    if (this.renderer && this.scene && this.camera) {
      this.renderer.render(this.scene, this.camera);
    }
  }

  // 动画
  animate(): void {
    //更新控制器
    this.render();

    //更新性能插件
    this.stats && this.stats.update();

    //更新相关位置
    if (this.gui) {
      if (this.light) {
        this.gui.lightY && (this.light.position.y = this.gui.lightY);
      }
      if (this.cube) {
        this.gui.cubeX && (this.cube.position.x = this.gui.cubeX);
        this.gui.cubeY && (this.cube.position.y = this.gui.cubeY);
        this.gui.cubeZ && (this.cube.position.z = this.gui.cubeZ);
      }
    }

    this.controls && this.controls.update();

    requestAnimationFrame(this.animate.bind(this));
  }

  initControls(): void {
    if (this.camera && this.renderer) {
      this.controls = new OrbitControls(this.camera, this.renderer.domElement);

      // 如果使用animate方法时，将此函数删除
      //this.controls.addEventListener( 'change', render );
      // 使动画循环使用时阻尼或自转 意思是否有惯性
      this.controls.enableDamping = true;
      //动态阻尼系数 就是鼠标拖拽旋转灵敏度
      //controls.dampingFactor = 0.25;
      //是否可以缩放
      this.controls.enableZoom = true;
      //是否自动旋转
      this.controls.autoRotate = false;
      //设置相机距离原点的最远距离
      this.controls.minDistance = 100;
      //设置相机距离原点的最远距离
      this.controls.maxDistance = 200;
      //是否开启右键拖拽
      this.controls.enablePan = true;
    }
  }

  initStats(): void {
    this.stats = Stats();
    document.body.appendChild(this.stats.dom);
  }
}
